package com.example.watertest;
import java.io.IOException;
import java.util.Calendar;
 
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.WakeLockOptions;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.ParallaxBackground;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.AnimatedSprite.IAnimationListener;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource;
import org.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureAtlasBuilder;
import org.andengine.opengl.texture.atlas.buildable.builder.ITextureAtlasBuilder.TextureAtlasBuilderException;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.ITiledTextureRegion;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.math.MathUtils;
import org.andengine.util.modifier.IModifier;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.CardinalSplineMoveModifier;
import org.andengine.entity.modifier.CardinalSplineMoveModifier.CardinalSplineMoveModifierConfig;
import org.andengine.entity.modifier.ColorModifier;
import org.andengine.entity.modifier.DelayModifier;
import org.andengine.entity.modifier.IEntityModifier;
import org.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.andengine.entity.modifier.IEntityModifier.IEntityModifierMatcher;
import org.andengine.entity.modifier.JumpModifier;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.MoveByModifier;
import org.andengine.entity.modifier.MoveModifier;
import org.andengine.entity.modifier.MoveXModifier;
import org.andengine.entity.modifier.ParallelEntityModifier;
import org.andengine.entity.modifier.PathModifier;
import org.andengine.entity.modifier.PathModifier.Path;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.modifier.ScaleModifier;
import org.andengine.entity.modifier.SequenceEntityModifier;
import org.andengine.input.touch.TouchEvent;

import android.graphics.Color;
import android.util.Log;


 
 
public class MainActivityanimated extends SimpleBaseGameActivity implements IOnSceneTouchListener {
 
protected static final IAnimationListener AnimatedSprite = null;
private Camera mCamera;
private static int WIDTH = 800;
private static int HEIGHT= 480;
private Font miFuente;
private BitmapTextureAtlas miAtlas;
private ITextureRegion texturaChar, texturaBoton;
private Sprite charSprite, Boton;
private ITiledTextureRegion texturaAnimada;
private AnimatedSprite spriteAnimado;
private Text miTexto;
private int cuenta = 0;
@Override
public EngineOptions onCreateEngineOptions() {
 
 
// Definimos nuestra camara
mCamera = new Camera(0, 0, WIDTH, HEIGHT);
// Ahora declaramos las opciones del motor
EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(), mCamera);
//EngineOptions(es full screen?, Cual es la orientacion de la pantalla?, Como actuaremos ante distintas resoluciones?, y la camara)
// impedimos que la pantalla se apague por inactividad
engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
// Return the engineOptions object, passing it to the engine
return engineOptions;
}
 
@Override
protected void onCreateResources() throws IOException {
 
//primero debemos indicar donde estan las imagenes
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
//luego crear el atlas, darle medidas y un tipo de textura.
miAtlas = new BitmapTextureAtlas(getTextureManager(), 800, 800, TextureOptions.BILINEAR);
//ubicamos nuestra imagen en el atlas
//texturaChar = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(miAtlas, this, "waterman.png", 0, 0,13,3);
//texturaChar= BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(miAtlas, this, "char.png",39, 56, 4, 10);
//Aqui ubicamos el sprite para que no se ubique sobre el anterior
//Osea teniendo en cuenta que el anterior estaba en 0,0 y ocupa hasta 75,95
//Lo ubicaremos despues 76 en x, 0 en y, e indicamos que tiene 10 columnas y 10 filas.
texturaAnimada = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(miAtlas, this, "watermanOK.png", 70, 60, 12, 3);
texturaBoton = BitmapTextureAtlasTextureRegionFactory.createFromAsset(miAtlas, this, "boton.png", 0, 200);

//y la cargamos
miAtlas.load();
//Aqui hemos creado un atlas de 256 x 256 para cargar una imagen de 108 x 253
//en el punto 0,0 de miAtlas, osea nos sobra espacio


//Indicamos donde se ubican las fuentes
FontFactory.setAssetBasePath("fuentes/");
//aqui creamos la textura donde cargaremos la fuente
final ITexture fontTexture = new BitmapTextureAtlas(getTextureManager(), 256, 256, TextureOptions.BILINEAR);
//Aqui definimos cual es la fuente, tamaño, si usara antialias y su color
miFuente = FontFactory.createFromAsset(getFontManager(), fontTexture, getAssets(), "fuente.ttf", 40, true, Color.BLUE);
//La cargamos
miFuente.load();



}


 
@Override
protected Scene onCreateScene() {
 
Scene sceneEjemplo = new Scene();


miTexto = new Text(mCamera.getWidth()*0.2f, mCamera.getHeight()*0.8f, miFuente, "Click:     1", getVertexBufferObjectManager()){
	
	int lastSecond = 0;

	@Override
		protected void onManagedUpdate(float pSecondsElapsed) {
		
		Calendar c = Calendar.getInstance();

	      /*
	      * We will only obtain the second for now in order to verify
	       * that it's time to update the Text's string
	      */
	      final int second = c.get(Calendar.SECOND);

	      /*
	       * If the last update's second value is not equal to the
	      * current...
	       */
	      if (lastSecond != second) {

		miTexto.setText("Click: " + second);
		cuenta++;
	      }

	  super.onManagedUpdate(pSecondsElapsed);
	}

	
	
};

/* Define the rectangle's width/height values */
final int rectangleDimensions = 80;
    
/* Define the initial rectangle position in the bottom 
 * left corner of the Scene */
final int initialPosition = (int) (rectangleDimensions * 0.5f);
    
/* Create the Entity which we will apply modifiers to */
Rectangle rectangle = new Rectangle(initialPosition, initialPosition, rectangleDimensions, rectangleDimensions, mEngine.getVertexBufferObjectManager());
Rectangle rectangle2 = new Rectangle(200, 200, rectangleDimensions, rectangleDimensions, mEngine.getVertexBufferObjectManager());
Rectangle rectangle3 = new Rectangle(300, 300, rectangleDimensions, rectangleDimensions, mEngine.getVertexBufferObjectManager());
Rectangle rectangle4 = new Rectangle(450, 300, rectangleDimensions, rectangleDimensions, mEngine.getVertexBufferObjectManager());
    
/* Set the rectangle's color to white so we can see it on the Scene */
rectangle.setColor(org.andengine.util.adt.color.Color.WHITE);
rectangle2.setColor(org.andengine.util.adt.color.Color.BLUE);
rectangle3.setColor(org.andengine.util.adt.color.Color.RED);
rectangle4.setColor(org.andengine.util.adt.color.Color.YELLOW);
    
/* Attach the rectangle to the Scene */
sceneEjemplo.attachChild(rectangle);
sceneEjemplo.attachChild(rectangle2);
sceneEjemplo.attachChild(rectangle3);
sceneEjemplo.attachChild(rectangle4);

/* LoopEntityModifier
 *  Define the move modifiers properties */
 float durat = 3;
 float fromX = 0;
 float toX = 100;

/* Create the move modifier */
MoveXModifier moveXModifier = new MoveXModifier(durat, fromX, toX);

/* Create a loop entity modifier, which will loop the move modifier
 *  indefinitely, or until unregistered from the rectangle.
 *  If we want to provide a loop count, we can add a second int parameter 
 *  to this constructor */
LoopEntityModifier loopEntityModifier = new LoopEntityModifier(moveXModifier,2);

/* register the loopEntityModifier to the rectangle */
rectangle2.registerEntityModifier(loopEntityModifier);





/*ParallelEntityModifier
 *  Scale modifier properties */
float scaleDuration = 2;
float fromScale = 1;
float toScale = 2;
/* Create a scale modifier */
ScaleModifier scaleModifier = new ScaleModifier(scaleDuration, fromScale, toScale);

/* Rotation modifier properties */
final float rotateDuration = 3;
final float fromRotation = 0;
final float toRotation = 360 * 4;
/* Create a rotation modifier */
RotationModifier rotationModifier = new RotationModifier(rotateDuration, fromRotation, toRotation);

/* Create a parallel entity modifier */
LoopEntityModifier parallelEntityModifier = new LoopEntityModifier( new ParallelEntityModifier(scaleModifier, rotationModifier));

/* Register the parallelEntityModifier to the rectangle */
rectangle3.registerEntityModifier(parallelEntityModifier);





/* Move modifier properties */
final float moveDuration = 2;
  fromX = initialPosition;
  toX = WIDTH * 0.5f;
final float fromY = initialPosition;
final float toY = HEIGHT * 0.5f;
/* Create a move modifier */
MoveModifier moveModifier = new MoveModifier(moveDuration, fromX, fromY, toX, toY);

/* Create a delay modifier */
DelayModifier delayModifier = new DelayModifier(2);

/* Scale modifier properties */

 scaleDuration = 2;

 fromScale = 1;
toScale = 1.5f;
/* Create a scale modifier */
ScaleModifier scaleModifiers = new ScaleModifier(scaleDuration, fromScale, toScale);

/* Create a sequence entity modifier */
SequenceEntityModifier sequenceEntityModifier = new SequenceEntityModifier(moveModifier, delayModifier, scaleModifiers);

/* Register the sequenceEntityModifier to the rectangle */
rectangle4.registerEntityModifier(sequenceEntityModifier);


/* Create the MoveModifier with the defined values */
//MoveModifier moveModifier = new MoveModifier(duration, fromX, fromY, toX, toY);
//SequenceEntityModifier moveModifier = new SequenceEntityModifier(new ScaleModifier(0.6f, 1, 1.5f), new ScaleModifier(0.6f, 1.5f, 1));

/* Register the moveModifier to our rectangle entity */
//rectangle.registerEntityModifier(moveModifier);

/* PathModifier 
 *  Create a list which specifies X coordinates to follow */
final float pointsListX[] = {
    initialPosition, /* First x position */
    WIDTH - initialPosition, /* Second x position */
    WIDTH - initialPosition, /* Third x position */
    initialPosition, /* Fourth x position */
    initialPosition /* Fifth x position */
};

/* Create a list which specifies Y coordinates to follow */
final float pointsListY[] = {
    initialPosition, /* First y position */
    HEIGHT - initialPosition, /* Second y position */
    initialPosition, /* Third y position */
    HEIGHT - initialPosition, /* Fourth y position */
    initialPosition /* Fifth y position */
};

/* Obtain the number of control points we have */
final int controlPointCount = pointsListX.length;

/* Create our Path object which we will pair our x/y coordinates into */
org.andengine.entity.modifier.PathModifier.Path path = new Path(controlPointCount);

/* Iterate through our point lists */
for(int i = 0; i < controlPointCount; i++){
  /* Obtain the coordinates of the control point at the index */
  final float positionX = pointsListX[i];
  final float positionY = pointsListY[i];

  /* Setup a new way-point by pairing together an x and y coordinate */
  path.to(positionX, positionY);
}

/* Movement duration */
final float duracion = 3;
/* Create the PathModifier */
PathModifier pathModifier = new PathModifier(duracion, path);

/* Register the pathModifier object to the rectangle */
//rectangle.registerEntityModifier(pathModifier);
/*  Termina PathModifier */    

/* Define the movement tension. Must be between -1 and 1 */
final float tension = 0f;

/* Create the cardinal spline movement modifier configuration */
CardinalSplineMoveModifierConfig config = new CardinalSplineMoveModifierConfig(controlPointCount, tension);
/* Iterate through our control point indices */
for(int index = 0; index < controlPointCount; index++){
  
  /* Obtain the coordinates of the control point at the index */
  final float positionX = pointsListX[index];
  final float positionY = pointsListY[index];
  
  /* Set position coordinates at the current index in the config object */
  config.setControlPoint(index, positionX, positionY);
}
/* Movement duration */
final float duration = 3;

/* Create the cardinal spline move modifier object */
CardinalSplineMoveModifier cardinalSplineMoveModifier = new CardinalSplineMoveModifier(duration, config);

/* Register the cardinalSplineMoveModifier object to the rectangle object */
rectangle.registerEntityModifier(cardinalSplineMoveModifier);



sceneEjemplo.attachChild(miTexto);
//(posicion x, posicion y, textura, elemento de andengine ignorenlo)
//charSprite = new Sprite(100, 200, texturaChar, getVertexBufferObjectManager());
spriteAnimado = new AnimatedSprite(100, 150,texturaAnimada, getVertexBufferObjectManager());
Boton = new Sprite(100, 100, texturaBoton, getVertexBufferObjectManager()){
	
	@Override
	public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY) {
		//(posicion x, posicion y, textura, elemento de andengine ignorenlo) - igual que arriba
		
			//Crearemos nuestro modifier, en este caso un JumpModifier (hay otros, movetoxmodifier, alphamodifier,etc etc etc)
			//JumpModofier(tiempo del salto, desdeX, hastaX, desdeY, hastaY, altura del Salto);	
		//spriteAnimado.registerEntityModifier(new MoveXModifier(1,120, 200));	
		//marcianoAnimado = new AnimatedSprite(39, 56,texturaChar, getVertexBufferObjectManager());
		//para animar el sprite debemos otorgarle tiempos en milisegundos a cada frame
		long[] duracionFrame = { 200, 200, 200, 200, 200, 200, 200};
		int[] Frames = { 6, 0, 1, 2, 3, 4, 5 };
		//long[] duracionFrames = { 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500};
		//( tiempos x frame, del frame 1 al 6, siempre repitiendose)
		//spriteAnimado.animate(duracionFrame, 6, 9, false);
		spriteAnimado.animate(duracionFrame, Frames , false, new IAnimationListener(){
			
			 @Override
		      public void onAnimationStarted(AnimatedSprite pAnimatedSprite,
		          int pInitialLoopCount) {
		        /* Fired when the animation first begins to run*/
	
				 
		      }

			@Override
			public void onAnimationFrameChanged(
					org.andengine.entity.sprite.AnimatedSprite pAnimatedSprite,
					int pOldFrameIndex, int pNewFrameIndex) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onAnimationLoopFinished(
					org.andengine.entity.sprite.AnimatedSprite pAnimatedSprite,
					int pRemainingLoopCount, int pInitialLoopCount) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onAnimationFinished(
					org.andengine.entity.sprite.AnimatedSprite pAnimatedSprite) {
				// TODO Auto-generated method stub
				
			}
			
		});
		//charSprite.detachSelf();
			
		
		
		return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
	}
	
};
//nunca se olviden de esto
sceneEjemplo.registerTouchArea(Boton);
sceneEjemplo.attachChild(Boton);

spriteAnimado.registerEntityModifier(new ScaleModifier(0.5f, 1, 2));


//marcianoAnimado.animate(duracionFrames, 1, 11, true);
//y lo añadimos a la escena
sceneEjemplo.attachChild(spriteAnimado);

//sceneEjemplo.attachChild(marcianoAnimado);

 
//sceneEjemplo.attachChild(charSprite);
return sceneEjemplo;


}

@Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
 
  
  return false;
}
 
}